package com.merry.websocket.ws;

import com.alibaba.fastjson.JSON;
import com.merry.websocket.config.GetHttpSessionConfigurator;
import com.merry.websocket.pojo.Message;
import com.merry.websocket.util.MessageUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zouyb
 * websocket 实现类
 */

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();

    private HttpSession httpSession;
    /**
     * 建立websocket连接后被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, ServerEndpointConfig config) throws IOException {
        //1.将session进行保存
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.put(user,session);
        //2.广播消息，需要将登录的所有的用户推送给所有的用户。
        String message = MessageUtils.getMessage(true,null,getFriends());
        broadcastAllUsers(message);
    }

    private Set getFriends(){
        Set<String> strings = onlineUsers.keySet();
        return strings;
    }

    private void broadcastAllUsers(String message) throws IOException {
        Set<String> users = onlineUsers.keySet();
        for (String user : users) {
            Session session = onlineUsers.get(user);
            session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 浏览器发送消息到服务端，该方法被调用
     * @param message
     */
    @OnMessage
    public void OnMessage(String message){
        //将消息推送给指定的用户
        Message message1 = JSON.parseObject(message,Message.class);
        //获取toName
        String toName = message1.getToName();
        String msg = message1.getMessage();
        //获取接收方的session对象
        Session session = onlineUsers.get(toName);
        String user = (String) this.httpSession.getAttribute("user");
        try {
            session.getBasicRemote().sendText(MessageUtils.getMessage(false,user,msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接时调用
     * @param session
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        //1.从 onlineUsers 中删除当前用户的session对象。
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.remove(user);
        //2.通知其他的所有用户。
        String message = MessageUtils.getMessage(true,null,getFriends());
        broadcastAllUsers(message);
    }

}
